package com.ruoyi.common.s7.ST30A;

import com.alibaba.fastjson2.JSON;
import com.github.s7connector.api.DaveArea;
import com.github.s7connector.api.S7Connector;
import com.ruoyi.common.s7.BaseVo;
import com.ruoyi.common.s7.ExchangeIntf;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class ST30AExchange implements ExchangeIntf {
    public  static int areaNumber = 5403;
    public static String ipAddress = "192.168.0.51";
    public static void main(String[] args) {
        ST30AHandle sT30Handle =   new ST30AHandle();
        S7Connector s7ReadConnector = sT30Handle.initConnect(ipAddress);
        ST30AVo st30Vo = sT30Handle.read(s7ReadConnector, areaNumber);
        if(st30Vo.getTotalFlag() ==1){
            log.info(JSON.toJSONString(st30Vo));

            S7Connector s7WriteConnector = sT30Handle.initConnect(ipAddress);
            byte[] bytes = {2};
            s7WriteConnector.write(DaveArea.DB, areaNumber, 87, bytes);
            try {
                s7WriteConnector.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     *
     * @return
     */
    @Override
    public BaseVo readPLC() {
        ST30AHandle sT30Handle =   new ST30AHandle();
        S7Connector s7Connector = sT30Handle.initConnect(ipAddress);
        ST30AVo st30Vo = sT30Handle.read(s7Connector, areaNumber);
        try {
            s7Connector.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return st30Vo;
    }

    /**
     *
     * @param sT30AVo
     */
    @Override
    public void writePLC(BaseVo sT30AVo) {
        ST30AVo st30AVo = (ST30AVo) sT30AVo;
        ST30AHandle sT30Handle =   new ST30AHandle();
        S7Connector s7Connector = sT30Handle.initConnect(ipAddress);
        //写入byte数组
        byte[] data = new byte[1];
        data[0] = st30AVo.getTotalFlag();
        s7Connector.write(DaveArea.DB, areaNumber, 87, data);
        try {
            s7Connector.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
